import Router from 'koa-router';
import { Context } from 'koa';
import { ChatMessage } from '../models/ChatMessage';
import { Character } from '../models/Character';
import { UserCharacterRelation } from '../models/UserCharacterRelation';
import { ResponseUtil } from '../utils/response';
import { validatePagination } from '../middleware/validation';
import { authenticateToken } from '../middleware/auth';
import { generateAIResponse } from '../utils/aiService';

const router = new Router();
const chatMessageModel = new ChatMessage();
const characterModel = new Character();
const userCharacterRelationModel = new UserCharacterRelation();

/**
 * 获取用户与角色的聊天记录
 * GET /api/chat/:characterId
 */
router.get('/:characterId', authenticateToken, validatePagination, async (ctx: Context) => {
  try {
    const userId = ctx.user?.id; // 从认证中间件获取用户ID
    if (!userId) {
      ctx.status = 401;
      ctx.body = ResponseUtil.error(ctx, '用户未认证', 'UNAUTHORIZED', 401);
      return;
    }
    const characterId = parseInt(ctx.params.characterId);
    const page = parseInt(ctx.query.page as string) || 1;
    const limit = parseInt(ctx.query.limit as string) || 20;

    if (isNaN(characterId)) {
      ctx.status = 400;
      ctx.body = ResponseUtil.error(ctx, '无效的角色ID', 'BAD_REQUEST', 400);
      return;
    }

    // 检查角色是否存在且激活
    const character = await characterModel.findById(characterId);
    if (!character) {
      ctx.status = 404;
      ctx.body = ResponseUtil.error(ctx, '角色不存在', 'NOT_FOUND', 404);
      return;
    }

    if (!character.is_active) {
      ctx.status = 403;
      ctx.body = ResponseUtil.error(ctx, '角色未激活', 'FORBIDDEN', 403);
      return;
    }

    const result = await chatMessageModel.getUserCharacterChatHistory(
      userId,
      characterId,
      { page, limit }
    );

    ctx.body = ResponseUtil.success(ctx, result, '获取聊天记录成功');
  } catch (error) {
    throw error;
  }
});

/**
 * 发送消息给角色
 * POST /api/chat/:characterId
 */
router.post('/:characterId', authenticateToken, async (ctx: Context) => {
  try {
    const userId = ctx.user?.id; // 从认证中间件获取用户ID
    if (!userId) {
      ctx.status = 401;
      ctx.body = ResponseUtil.error(ctx, '用户未认证', 'UNAUTHORIZED', 401);
      return;
    }
    const characterId = parseInt(ctx.params.characterId);
    const { content } = ctx.request.body;

    if (isNaN(characterId)) {
      ctx.status = 400;
      ctx.body = ResponseUtil.error(ctx, '无效的角色ID', 'BAD_REQUEST', 400);
      return;
    }

    if (!content || content.trim() === '') {
      ctx.status = 400;
      ctx.body = ResponseUtil.error(ctx, '消息内容不能为空', 'BAD_REQUEST', 400);
      return;
    }

    // 检查角色是否存在且激活
    const character = await characterModel.findById(characterId);
    if (!character) {
      ctx.status = 404;
      ctx.body = ResponseUtil.error(ctx, '角色不存在', 'NOT_FOUND', 404);
      return;
    }

    if (!character.is_active) {
      ctx.status = 403;
      ctx.body = ResponseUtil.error(ctx, '角色未激活', 'FORBIDDEN', 403);
      return;
    }

    // 保存用户消息
    const userMessage = await chatMessageModel.create({
      user_id: userId,
      character_id: characterId,
      content,
      is_user_message: true
    });

    // 获取最近的聊天历史作为上下文
    const recentMessages = await chatMessageModel.getRecentMessages(userId, characterId, 10);

    // 生成AI回复
    const aiResponse = await generateAIResponse(
      content,
      character,
      recentMessages
    );

    // 保存AI回复
    const aiMessage = await chatMessageModel.create({
      user_id: userId,
      character_id: characterId,
      content: aiResponse,
      is_user_message: false
    });

    // 更新用户与角色的关系（最后互动时间）
    await userCharacterRelationModel.updateLastInteractionTime(userId, characterId);

    ctx.body = ResponseUtil.success(ctx, {
      userMessage,
      aiMessage
    }, '发送消息成功');
  } catch (error) {
    throw error;
  }
});

/**
 * 获取用户所有聊天记录
 * GET /api/chat
 */
router.get('/', authenticateToken, validatePagination, async (ctx: Context) => {
  try {
    const userId = ctx.user?.id; // 从认证中间件获取用户ID
    if (!userId) {
      ctx.status = 401;
      ctx.body = ResponseUtil.error(ctx, '用户未认证', 'UNAUTHORIZED', 401);
      return;
    }
    const page = parseInt(ctx.query.page as string) || 1;
    const limit = parseInt(ctx.query.limit as string) || 20;

    const result = await chatMessageModel.getUserAllChatHistory(userId, { page, limit });

    ctx.body = ResponseUtil.success(ctx, result, '获取聊天记录成功');
  } catch (error) {
    throw error;
  }
});


export default router;